﻿using System;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using Medianamik.Core;
using Medianamik.Core.Security;
using Medianamik.Globalization;
using Medianamik.UI.Controls;

namespace Medianamik.UI.ConfigManagement
{
    public partial class PageManagement : BaseModuleEditionPage<MedianamikPage>
    {
        protected const string LIST_PAGE = "PageList.aspx?tab=1";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                chkRoles.DataBind();
            }
        }

        protected override void Save(object sender, EventArgs e)
        {
            if (IsValid)
            {
                var page = MedianamikFormTemplate.GetFormValue(CurrentNode);
                NodeManager.SaveNode(page);

                var selectedRoles = chkRoles.Items.Cast<ListItem>()
                    .Where(i => i.Selected).Select(i => i.Value);

                var notSelectedRoles = chkRoles.Items.Cast<ListItem>()
                    .Select(i => i.Value).Except(selectedRoles);

                SecurityManager.RemoveRolesFromPage(page,notSelectedRoles.ToArray());
                SecurityManager.AddRolesToPage(page,selectedRoles.ToArray());

                Translator.CreateResource("SiteMap", page.FileName, page.GetValues<String>("Name"));
                //Reset du Menu
                ((MedianamikSiteMapProvider)SiteMap.Provider).Rebuild();
                Response.Redirect(ReturnURL);
            }
        }

        public override MedianamikFormTemplate MedianamikFormTemplate
        {
            get { return Fields; }
        }

        protected override string ReturnURL
        {
            get
            {
                return LIST_PAGE;
            }
        }

        public override Guid? TypeId
        {
            get
            {
                return MedianamikTypes.MedianamikPage ;
            }
        }

        public override LinkButton SaveButton
        {
            get { return btnSave; }
        }

        protected override Guid? ParentNodeId
        {
            get
            {
                return MedianamikModules.ConfigManagement;
            }
        }

        protected string[] GetSelectedRoles()
        {
            return CurrentNode.GetRoles().Select(r => r.RoleName).ToArray();
        }
    }
}